//
//  YWVideoViewController.m
//  网易新闻
//
//  Created by Yeewii@hotmail.com on 16/6/16.
//  Copyright © 2016年 Yeewii@hotmail.com. All rights reserved.
//

#import "YWVideoViewController.h"
#import "YWVideoCollectioCell.h"
#import "YWHttpTool.h"
#import "YWVideoDataModels.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <UIView+SDAutoLayout.h>
#import "HSDownloadManager.h"
#import <MJRefresh.h>
#import "WMPlayer.h"

@interface YWVideoViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,WMPlayerDelegate>
@property (nonatomic,strong) UICollectionView *collection;
//@property (nonatomic , strong) MPMoviePlayerController *movie;
@property (nonatomic,copy) NSArray *itemArray;
@property (nonatomic,strong) NSIndexPath *selectIndexPath;
@end

@implementation YWVideoViewController
{
    WMPlayer *YWPlayer;
}
static NSString * const reuseIdentifier = @"YWVideoCollectioCell";

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [YWPlayer releasePlay];
    YWPlayer = nil;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self requestData];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    __weak typeof(self) weakSelf = self;
    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf requestData];
    }];
    
    [self requestData];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieDidFinish) name:MPMoviePlayerPlaybackDidFinishNotification object:self.movie];
}


-(UICollectionView *)collection
{
    if (!_collection)
    {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection             = UICollectionViewScrollDirectionVertical;
        _collection                            = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, MAINWIDTH, MAINHEIGHT) collectionViewLayout:flowLayout];
        _collection.backgroundColor            = [UIColor whiteColor];
        _collection.delegate                   = self;
        _collection.dataSource                 = self;
        [self.view addSubview:_collection];
        [_collection registerNib:[UINib nibWithNibName:reuseIdentifier bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
        flowLayout.sectionInset                = UIEdgeInsetsMake(50, 10, 50, 10);
    }
    return _collection;
}

-(void)requestData
{
    
    __weak typeof(self) weakSelf = self;
    [YWHttpTool GET:VIDEOURL params:nil success:^(NSDictionary *responseObject) {
        
        YWVideoNSObject *dataObj = [YWVideoNSObject modelObjectWithDictionary:responseObject];
        _itemArray = dataObj.myProperty1;
        [weakSelf.collection reloadData];
        [weakSelf.collection.mj_header endRefreshing];
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(MAINWIDTH/2.0-15, 200);
}
#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    YWVideoInternalBaseClass1 *model = _itemArray[indexPath.row];
    __weak YWVideoCollectioCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.model = model;
    cell.progress = 0;
//    cell.downLoadBlock = ^{
//    
//        [[HSDownloadManager sharedInstance]download:model.mp4Url progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if ([model.mp4Url isEqualToString:cell.model.mp4Url])
//                {
//                    cell.progress = progress;
//                }
//            });
//        } state:^(DownloadState state) {
//            dispatch_async(dispatch_get_main_queue(), ^{
//               
//                [cell.downLoadBtn setTitle:[NSString stringWithFormat:@"%d",state] forState:UIControlStateNormal];
//                
//            });
//        }];
//    
//    };
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    YWVideoInternalBaseClass1 *model = _itemArray[indexPath.row];
//    if (self.movie)
//    {
//        [self.movie.view removeFromSuperview];
//    }
//    self.movie = [MPMoviePlayerController new];
//    self.movie.contentURL = [NSURL URLWithString:model.mp4Url];
    [self playWithUrl:model.mp4Url indexPath:indexPath];
    
//    YWVideoCollectioCell *cel = (YWVideoCollectioCell* )[collectionView cellForItemAtIndexPath:indexPath];
//    self.movie.view.frame  = cel.bounds;
//    [cel addSubview:self.movie.view];
//    self.movie.controlStyle = MPMovieControlStyleNone;
//    [self.movie play];
    _selectIndexPath = indexPath;
    
}



-(void)playWithUrl:(NSString *)url indexPath:(NSIndexPath *)indexPath
{
    if (YWPlayer)
    {
        [YWPlayer releasePlay];
        YWPlayer = nil;
    }
    NSLog(@"%ld",indexPath.row);
    YWVideoCollectioCell *tempCell = (YWVideoCollectioCell *)[self.collection cellForItemAtIndexPath:indexPath];
    NSLog(@"%@",NSStringFromCGRect(tempCell.frame));
    YWPlayer = [[WMPlayer alloc]initWithFrame:tempCell.bounds];
    YWPlayer.delegate = self;
    YWPlayer.closeBtnStyle = CloseBtnStyleClose;
    YWPlayer.URLString = url;
    [YWPlayer play];
    [tempCell addSubview:YWPlayer];
    [tempCell bringSubviewToFront:YWPlayer];
}







-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    YWVideoCollectioCell *cel = (YWVideoCollectioCell* )[self.collection cellForItemAtIndexPath:_selectIndexPath];
    CGRect rect = cel.bounds;
//    [self.movie.view removeFromSuperview];
    __block CGRect tempRect = CGRectZero;
//    if (!self.movie.view.hidden)
//    {
    if (!YWPlayer)
    {
        return;
    }
        if (cel.width == 0)
        {
            if (![YWPlayer.superview isMemberOfClass:[UIView class]])
            {
                YWPlayer.frame = CGRectMake(0, 200, MAINWIDTH, 300);
                [self.view addSubview:YWPlayer];
                [UIView animateWithDuration:1 animations:^{
                    tempRect = YWPlayer.frame;
                } completion:^(BOOL finished) {
//                    tempRect = YWPlayer.frame;
                }];
            }
            
        }else
        {
            if (![YWPlayer.superview isMemberOfClass:[UICollectionViewCell class]])
            {
                YWPlayer.frame = rect;
                [cel addSubview:YWPlayer];
                
                [UIView animateWithDuration:1 animations:^{
                   tempRect = YWPlayer.frame;
                } completion:^(BOOL finished) {
//                    tempRect = YWPlayer.frame;
                }];
            }
            
        }
//    }
    
}
//#pragma mark - 监听 -
//-(void)movieDidFinish
//{
//    [self.movie.view removeFromSuperview];
//    self.movie.view.hidden = YES;
//    [self.collection reloadData];
//}
//-(void)viewDidDisappear:(BOOL)animated
//{
//    [super viewDidDisappear:animated];
//    [self.movie.view removeFromSuperview];
//    self.movie.view.hidden = YES;
//}

///播放状态
-(void)wmplayerFailedPlay:(WMPlayer *)wmplayer WMPlayerStatus:(WMPlayerState)state{
    NSLog(@"wmplayerDidFailedPlay");
}
-(void)wmplayerReadyToPlay:(WMPlayer *)wmplayer WMPlayerStatus:(WMPlayerState)state{
    NSLog(@"wmplayerDidReadyToPlay");
}
-(void)wmplayerFinishedPlay:(WMPlayer *)wmplayer{
    NSLog(@"wmplayerDidFinishedPlay");
//    VideoCell *currentCell = (VideoCell *)[self.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:currentIndexPath.row inSection:0]];
//    [currentCell.playBtn.superview bringSubviewToFront:currentCell.playBtn];
    [wmplayer releasePlay];
    YWPlayer = nil;
    [self setNeedsStatusBarAppearanceUpdate];
}

-(void)setUpFullScreen
{
    if (!YWPlayer)
    {
        return;
    }
    [YWPlayer removeFromSuperview];
    YWPlayer.frame = CGRectMake(0, 0, MAINWIDTH, MAINHEIGHT);
    YWPlayer.playerLayer.frame = CGRectMake(0, 0, MAINWIDTH, MAINHEIGHT);
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:YWPlayer];
//    YWPlayer.transform = CGAffineTransformMakeRotation(M_PI_2);
}

//点击播放暂停按钮代理方法
-(void)wmplayer:(WMPlayer *)wmplayer clickedPlayOrPauseButton:(UIButton *)playOrPauseBtn;
{

}
//点击关闭按钮代理方法
-(void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn;
{
    YWPlayer = nil;
}
//点击全屏按钮代理方法
-(void)wmplayer:(WMPlayer *)wmplayer clickedFullScreenButton:(UIButton *)fullScreenBtn;
{
    [self setUpFullScreen];
}
//单击WMPlayer的代理方法
-(void)wmplayer:(WMPlayer *)wmplayer singleTaped:(UITapGestureRecognizer *)singleTap;
{
    
}
//双击WMPlayer的代理方法
-(void)wmplayer:(WMPlayer *)wmplayer doubleTaped:(UITapGestureRecognizer *)doubleTap;
{
    
}
@end
